<template>
  <div>
    <el-row :gutter="20" class="mb8" style="align-items: center">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
        >添加饭店</el-button>
      </el-col>
      <el-col v-if="match?.isFood==1" :span="1.5">
        饭店可预定时间：{{ parseTime(match?.foodStart,'{y}-{m}-{d}') }} ~ {{ parseTime(match?.foodEnd,'{y}-{m}-{d}') }}
      </el-col>
      <el-col v-if="match?.isFood==1" :span="1.5">
        饭店退订截止时间：{{ parseTime(match?.foodOff,'{y}-{m}-{d}') }}
      </el-col>
      <el-col v-if="match?.isFood==1" :span="1.5">
        餐饮下单截止时间：{{ parseTime(match?.foodLast,'{y}-{m}-{d}') }}
      </el-col>
      <el-col v-if="match?.isFood==1" :span="1.5">
        <el-button type="text" style="color: orange" @click="handleUpdateActive()">修改</el-button>
      </el-col><right-toolbar :search="false" @queryTable="getList" />
    </el-row>

    <el-table
      ref="tableRef" v-loading="loading" :data="diningList" row-key="id" :expand-row-keys="[]"
      @expand-change="handleExpandChange"
    >
      <el-table-column type="expand" width="30">
        <template #default="props">
          <el-row justify="center">
            <el-table v-loading="props.row.loading" :data="props.row.foods" style="width: 95%">
              <el-table-column label="食品图片" width="150" align="center" prop="photos">
                <template #default="scope">
                  <el-image style="width: 40px;height: 40px" :src="scope.row.photos.split(',')[0]" :preview-src-list="scope.row.photos.split(',')" />
                </template>
              </el-table-column>
              <el-table-column label="食品名称" min-width="100" align="center" prop="name" />
              <el-table-column label="餐别" align="center" prop="category">
                <template #default="scope">
                  {{ ['早餐','午餐','晚餐'][scope.row.category] }}
                </template>
              </el-table-column>
              <el-table-column label="价格" prop="foodPrice" align="center" min-width="100">
                <template #default="scope">
                  <el-input v-if="scope.row.isEdit" v-model="scope.row.foodPrice" @keyup.enter="handleUpdateFood(props.row,scope.row)" />
                  <span v-else>{{ scope.row.foodPrice }}</span>
                </template>
              </el-table-column>
              <el-table-column label="配送时间" min-width="200" align="center">
                <template #default="scope">
                  <el-time-picker
                    v-if="scope.row.isEdit"
                    v-model="scope.row.psTime"
                    style="width: 100%"
                    is-range
                    range-separator="~"
                    format="HH:mm"
                    value-format="HH:mm"
                    :editable="false"
                    :clearable="false"
                    @keyup.enter="handleUpdateFood(props.row,scope.row)"
                  />
                  <span v-else>{{ scope.row.psStart?`${scope.row.psStart} ~ ${scope.row.psEnd}`:'--' }}</span>
                </template>
              </el-table-column>
              <el-table-column label="配送地点" prop="address" align="center" min-width="200">
                <template #default="scope">
                  <el-input v-if="scope.row.isEdit" v-model="scope.row.address" placeholder="请输入配送地址" @keyup.enter="handleUpdateFood(props.row,scope.row)" />
                  <span v-else>{{ scope.row.address }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" fixed="right" width="150" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                  <el-button v-if="scope.row.isEdit" type="text" @click="handleUpdateFood(props.row,scope.row)">确定</el-button>
                  <el-button v-else type="text" @click="handleModifyRow(scope.row)">编辑</el-button>
                  <el-button v-if="scope.row.isEdit" type="text" @click="handleCancelRow(scope.row)">取消</el-button>
                  <el-button type="text" @click="handleDeleteFood(props.row,scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column type="index" width="55" label="序号" align="center" />
      <el-table-column label="饭店图片" align="center" prop="photos" width="150">
        <template #default="scope">
          <el-image style="width: 40px;height: 40px" :src="scope.row.photos.split(',')[0]" :preview-src-list="scope.row.photos.split(',')" />
        </template>
      </el-table-column>
      <el-table-column label="饭店名称" align="center" prop="name" />
      <el-table-column label="饭店地址" align="center" prop="addName" :show-overflow-tooltip="true" />
      <el-table-column label="操作" fixed="right" width="150" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button type="text" @click="handleAddFood(scope.row)">选择食品</el-button>
          <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <add-dining ref="addDiningRef" @complete="getList" />
    <add-food ref="addFoodRef" @complete="getFoodList" />
  </div>
</template>

<script setup>

import { getCurrentInstance, ref } from 'vue'
import { useRoute } from 'vue-router'
import { delMatchDining, getActivity, getMatchDining } from '@/api/logex/activity'
import AddDining from './dialog/addDining'
import AddFood from './dialog/addFood'
import { delActivityFood, listActivityFood, putData } from '@/api/logex/activityFood'
import _ from 'lodash'

const { proxy } = getCurrentInstance()
const emit = defineEmits(['modifyTime'])
const route = useRoute()

const match = ref(null)
const diningList = ref([])
const loading = ref(true)

const matchId = route.params.matchId

function getList() {
  loading.value = true
  diningList.value = []

  getMatchDining({
    activityId: matchId
  }).then(res => {
    loading.value = false
    diningList.value = res.rows
  })
}

function getMatch() {
  getActivity(matchId).then(response => {
    match.value = response.data
  })
}

function handleUpdateActive() {
  emit('modifyTime')
}

function handleAdd() {
  proxy.$refs['addDiningRef'].open({
    matchId: matchId
  })
}

function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除饭店"' + row.name + '"的数据项？').then(function() {
    loading.value = true
    return delMatchDining(row.id)
  }).then(() => {
    getMatchDining({
      activityId: matchId
    }).then(res => {
      diningList.value = res.rows
    })

    proxy.$modal.msgSuccess('删除成功')
  }).finally(() => {
    loading.value = false
  })
}

function handleAddFood(row) {
  proxy.$refs['addFoodRef'].open({
    rowId: row.id,
    matchId: row.activityId,
    restaurantId: row.restaurantId
  })
}

function handleExpandChange(row) {
  if (!row.foods) {
    row.loading = true
    listActivityFood({
      larId: row.id
    }).then(res => {
      row.loading = false
      row.foods = res.rows
    })
  }
}

defineExpose({
  init: () => {
    getList()
    getMatch()
  },
  getMatch
})

//#region 食品操作
function handleModifyRow(row) {
  const { foodPrice, address, psStart, psEnd, psTime } = row
  row.baseData = { foodPrice, address, psStart, psEnd, psTime }
  row.isEdit = true
}

function handleCancelRow(row) {
  row.foodPrice = row.baseData.foodPrice
  row.address = row.baseData.address
  row.psStart = row.baseData.psStart
  row.psEnd = row.baseData.psEnd
  row.psTime = row.baseData.psTime
  row.isEdit = false
}

function handleUpdateFood(dining, row) {
  if (parseFloat(row.foodPrice) != row.foodPrice) {
    proxy.$modal.msgError('请输入正确的价格')
    return
  }
  if (!row.psTime || row.psTime.length == 0) {
    proxy.$modal.msgError('请选择配送时间')
    return
  }
  if (!row.address) {
    proxy.$modal.msgError('请输入配送地址')
    return
  }

  row.psStart = row.psTime[0]
  row.psEnd = row.psTime[1]

  dining.loading = true
  putData({
    id: row.id,
    foodPrice: row.foodPrice,
    address: row.address,
    psStart: row.psStart,
    psEnd: row.psEnd
  }).then(res => {
    proxy.$modal.msgSuccess('更新成功')
    row.isEdit = false
  }).finally(() => {
    dining.loading = false
  })
}

function handleDeleteFood(dining, food) {
  proxy.$modal.confirm('是否确认删除食品"' + food.name + '"的数据项？').then(function() {
    dining.loading = true
    return delActivityFood(food.id)
  }).then(() => {
    listActivityFood({
      larId: dining.id
    }).then(res => {
      dining.foods = res.rows
    })
    proxy.$modal.msgSuccess('删除成功')
  }).finally(() => {
    dining.loading = false
  })
}

function getFoodList(rowId) {
  const dining = _.find(diningList.value, (h) => {
    return h.id === rowId
  })

  dining.loading = true
  listActivityFood({
    larId: rowId
  }).then(res => {
    dining.loading = false
    dining.foods = res.rows

    proxy.$refs['tableRef'].toggleRowExpansion(dining, true)
  })
}

//#endregion

</script>

<style scoped>

</style>
